<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<!-- <el-form-item label="友商名称：">
                            <el-input v-model="transferVal" placeholder="请输入搜索友商名称" />
                        </el-form-item> -->

						<el-form-item>
							<el-button v-if="$hasPer('SupplierBasicInfo1:add')" @click="nodeClick" icon="ele-Plus" type="primary"> 新增 </el-button>
							<el-button v-if="$hasPer('SupplierBasicInfo7:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table ref="excelRef" :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="友商名称" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="v_ProvideName" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.v_ProvideName }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="产品名称" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="product_Name" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.product_Name }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="产品描述" align="center">
											<template #default="scope">
												<span v-if="scope.row.product_Description">{{ scope.row.product_Description }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdTime" label="创建时间" align="center" />
										<el-table-column min-width="100" :show-overflow-tooltip="true" prop="createdUserName" label="创建人" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="updatedTime" label="更新时间" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedTime">{{ scope.row.updatedTime }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="100" :show-overflow-tooltip="true" prop="updatedUserName" label="更新人" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedUserName">{{ scope.row.updatedUserName }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="140" :label="$t('qNuJ1BpqhakfykxAewQs')" align="center" fixed="right">
											<el-table-column min-width="140" fixed="right" align="center">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询 </el-button>
													<el-button @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
												</template>
												<template #default="scope">
													<div class="operate-s">
														<el-button v-if="$hasPer('SupplierBasicInfo2:edit')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary"> 编辑</el-button>
														<el-button v-if="$hasPer('SupplierBasicInfo3:create')" size="small" @click="documentClick(scope.row)" text type="primary"> 附件管理 </el-button>
														<el-button v-if="$hasPer('SupplierBasicInfo4:delete')" @click="deleteHandle(scope.row.n_Id, getData)" class="icon-e" icon="ele-Delete" size="small" text type="danger">
															删除
														</el-button>
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible" :title="editId ? '编辑' : '新增'" width="50%" @close="cancelUseClick">
			<el-form :model="ruleForm" label-width="120px" ref="formRef" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="providerId" label="友商名称">
							<el-select v-model="ruleForm.providerId" placeholder="友商名称" clearable style="width: 100%">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="productName" label="产品名称">
							<el-input v-model="ruleForm.productName" placeholder="产品名称" clearable />
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="" label="产品描述">
							<el-input v-model="ruleForm.productDescription" placeholder="产品描述" clearable />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(formRef, getData)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 文件 -->
		<uploadFile :fileInfo="fileInfo" :isShowUploadDialog="fileDialog" @closeUploadDialog="cancelFileClick" @controlFileClick="controlFileClick" @updateData="getData" />
	</div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import getTableData from '/@/utils/getTableData';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import { sysDictDataList } from '/@/api/centerControl/pubilc';
import { getSupplierBasicInfoPageApi, deleteSupplierBasicInfoApi, addSupplierBasicInfoApi, updateSupplierBasicInfoApi, getSupplierBasicInfoApi2 } from '/@/api/centerControl/allInterface';
import uploadFile from './uploadFile.vue';
import SearchModel from '/@/views/oms/component/search-model.vue';
import { exportToExcel } from '/@/utils/exportToExcel';
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';
const { proxy } = useCurrentInstance();
const $t = proxy.$t;
let searchObj: any = reactive({});
const ruleForm = reactive({
	providerId: '',
	productName: '',
	productDescription: '',
});

/***** searchClick 查询按钮 *****/
const searchClick = () => {
	// searchObj.ProviderName = transferVal.value
	let newObj = Object.keys(searInfo.value);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = searInfo.value[i];
		});
	}
};

const resetClick = () => {
	searInfo.value = {};
	let newObj = Object.keys(searchObj);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = '';
			// console.log(i);
		});
	}
	initInfoFun();
};

/*** nodeClick 新增/编辑 校验 */
const formRef = ref<FormInstance>();
const rules = reactive({
	providerId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	productName: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
});

/*** nodeClick 新增/编辑点击事件 */
const showDialogVisible = ref(false);
const editId = ref(0);
const nodeClick = async (obj: any) => {
	if (obj.n_Id) {
		editId.value = obj.n_Id;
		ruleForm.providerId = obj.provider_Id;
		ruleForm.productName = obj.product_Name;
		ruleForm.productDescription = obj.product_Description;
	}
	showDialogVisible.value = true;
};

/*** cancelUseClick 取消事件 */
const cancelUseClick = () => {
	showDialogVisible.value = false;
	formRef.value?.resetFields();
	editId.value = 0;
	// 基本信息
	ruleForm.providerId = '';
	ruleForm.productName = '';
	ruleForm.productDescription = '';
};

/*** controlUseClick 提交事件 */
const controlUseClick = async (formEl: FormInstance | undefined, updateFun: Function) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			console.log('submit!');
			if (editId.value) {
				updateSupplierBasicInfoApi({ ...ruleForm, id: editId.value }).then((res: any) => {
					console.log(res, 'res');
					cancelUseClick();
					updateFun();
				});
			} else {
				const obj = Object.assign({ ...ruleForm, N_Id: 0 });
				addSupplierBasicInfoApi(obj).then((res: any) => {
					console.log(res, 'res');
					cancelUseClick();
					updateFun();
				});
			}
		} else {
			console.log('error submit!', fields);
		}
	});
};

/*** deleteHandle 删除数据事件 */
const deleteHandle = async (val: String | Number, updateFun: Function) => {
	ElMessageBox.confirm($t('ps5xm1Fk4H9FduSi7ljhW'), $t('imXkp2fMe2jXax1e9yR91'), {
		confirmButtonText: $t('vs4icKxkP7sr74uXwUoxR'),
		cancelButtonText: $t('tbKfNeTsqNeN8UaxlQlQm'),
		type: 'warning',
	})
		.then(async () => {
			let param = { id: val };
			try {
				let res: any = await deleteSupplierBasicInfoApi(param);
				if (res.success) {
					updateFun();
				}
			} catch (err) {
				return;
			}
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: $t('oWdtapHuvktLiQJySdnJx'),
			});
		});
};

/*** 附件管理 */
const fileInfo = ref();
const fileDialog = ref(false);
/*** cancelFileClick 文件上传取消事件 */
const cancelFileClick = (val: boolean) => {
	fileDialog.value = val;
};

/*** controlFileClick 文件上传提交事件 */
const controlFileClick = () => {
	fileDialog.value = false;
};

/*** documentClick 文档下载事件 */
const documentClick = async (val: any) => {
	fileInfo.value = JSON.stringify(val);
	fileDialog.value = true;
};

/*** 初始化数据 */
const basicsInfo: any = ref([]);
const initInfoFun = () => {
	basicsInfo.value = [
		{
			typeId: 'product_Name', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'ProductName', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '产品名称', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
		{
			typeId: 'v_ProvideName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'ProviderId', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '友商名称', // placeholder数据
			defaultProp: options1.value, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
	];
};

const searInfo: any = ref();
const searchHandel = (val: any) => {
	searInfo.value = val;
};

/*** ================================= 导出数据函数操作 ================================= */
const excelRef: any = ref(null);
const handleExport = () => {
	if (excelRef.value) {
		if (excelRef.value.data.length !== 0) {
			let tableExcel: any = [];
			let tableArr = excelRef.value.data;
			tableArr.map((item: any) => {
				let tableObj: any = {};
				tableObj['友商名称'] = item.v_ProvideName ? item.v_ProvideName : '-';
				tableObj['产品名称'] = item.product_Name ? item.product_Name : '-';
				tableObj['产品描述'] = item.product_Description ? item.product_Description : '-';

				tableObj['创建人'] = item.createdUserName ? item.createdUserName : '-';
				tableObj['创建时间'] = item.createdTime ? item.createdTime : '-';
				tableObj['更新人'] = item.updatedUserName ? item.updatedUserName : '-';
				tableObj['更新时间'] = item.updatedTime ? item.updatedTime : '-';
				tableExcel.push(tableObj);
			});
			exportToExcel(tableExcel, '供应商基本信息.xlsx');
		} else {
			ElMessage({
				type: 'error',
				message: '暂无数据导出',
			});
		}
	}
};

const options1: any = ref([]);
onMounted(async () => {
	const res = await getSupplierBasicInfoApi2();
	options1.value = res.data.map((item: any) => {
		return {
			label: item.v_ProvideName,
			value: item.n_Id,
		};
	});
	await initInfoFun();
});

const { handleCurrentChange, pageSize, pageNo, handleSizeChange, totalRows, list, indexMethod, loading, getData } = getTableData(getSupplierBasicInfoPageApi, {}, searchObj);
</script>
<style lang="scss">
@import '../style/public.scss';
</style>
<style scoped lang="scss">
#friend-merchant-manage {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}

	.upload-s {
		:deep(.el-upload--picture-card) {
			background-color: rgba(255, 255, 255, 0) !important;
		}
	}
}
</style>
